package com.tech.koufu.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.Volley;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R; 
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.model.TrackerUser;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.adapter.ExpertsShowAdapter; 
import com.umeng.analytics.MobclickAgent;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * @ClassName: ExpertsActivity
 * @Description: 1:盈利牛人 2：人气牛人 3:我的关注 
 * @author luo
 * @date 2015年3月26日 下午9:05:47
 */
public class ExpertsActivity extends Activity implements OnClickListener{
	public static final String TAG = ExpertsActivity.class.getName();
	private Context mContext;
	private int page = 1;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private ExpertsShowAdapter mAdapter;
	private String urlName;
	/**
	 * 1:盈利牛人 2：人气牛人 3:我的关注
	 */
	private int type;
	
//	private RequestQueue mQueue; 
	private MyApplication myApp;
//	CookieStringRequest stringRequest;
	BitmapUtils bitmapUtils;
	private ArrayList<TrackerUser> datas;
	private String userid;
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_experts); 
		myApp = (MyApplication) getApplication();
		mContext = this;
		initView(); 
		initData();
	}
	
	 @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(mContext);
	}
	 
	 @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(mContext);
	}
	private void initView() { 
		findViewById(R.id.img_callback).setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.tv_title);
		type = getIntent().getIntExtra("status", 1);
		userid = getIntent().getStringExtra("userid");
		if(userid==null){
			userid = myApp.getUserid();
		}
		if(type==1){//盈利牛人
			title.setText(R.string.title_experts_profitableman);
			urlName = Statics.IF_NIUREN; 
		}else if(type==2){//人气牛人
			title.setText(R.string.title_hot_profitableman);
			urlName = Statics.IF_RENQI;
		}else if(type ==3){
			if(userid!=null && myApp.getUserid().equals(userid)){
				title.setText(R.string.menu_myAttention);
			}else{
				title.setText(R.string.txt_concern);
			}
			urlName = Statics.IF_myConcern;
		}
		
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.lv_pull);
		actualListView = mPullToRefreshListView.getRefreshableView(); 
        registerForContextMenu(actualListView);
        bitmapUtils =  new BitmapUtils(this);
        mAdapter = new ExpertsShowAdapter(getApplicationContext(),type,bitmapUtils,myApp.digitalid, myApp.groupId);
		actualListView.setAdapter(mAdapter);
		actualListView.setOnItemClickListener(itemClick);
	}
	private void initData(){
		datas = new ArrayList<TrackerUser>();
//		mQueue = Volley.newRequestQueue(getApplicationContext());  
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	datas.clear();
		        	page=1; 
		        }else {
		        	page++; 
		        }  
				load();
			}
		});
		mPullToRefreshListView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true));
		mPullToRefreshListView.setRefreshing(true);
		mPullToRefreshListView.setMode(Mode.BOTH);
		mAdapter.sessionID = myApp.phpsessid;
		mAdapter.userId = myApp.digitalid;
		mAdapter.groupId = myApp.groupId;
//		mAdapter.mQueue = mQueue;
	}
 
	private void load(){
		String url = Statics.URL_PHP+urlName; 
		try {
			CookieStringRequest stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

				@Override
				public void onResponse(String response) {   
					if(!TextUtils.isEmpty(response)){
						try { 
							Log.d("niuren", response);
							JSONObject obj = new JSONObject(response);
							String status = obj.optString("status");
							if(status.equals("0")){
								JSONArray arry = obj.optJSONArray("data");
								if(arry!=null){
									int length = arry.length();
									for(int i=0;i<length;i++){
										JSONObject o = arry.getJSONObject(i);
										TrackerUser cg = new TrackerUser(o,type);
										datas.add(cg);
									}
									if(null!=datas && datas.size()>0){
										mAdapter.datas = datas;
										mAdapter.notifyDataSetChanged(); 
									}  
								}else{
									page--;
								}
							}else{  
							}
						} catch (JSONException e) { 
							e.printStackTrace();
						}
					}
					mPullToRefreshListView.onRefreshComplete();
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) { 
					error.printStackTrace();
					mPullToRefreshListView.onRefreshComplete();
				}
			}){
				@Override
				protected Map<String, String> getParams() throws AuthFailureError { 
					Map<String, String> params = new HashMap<String, String>();
					params.put("page", page+"");     
					params.put("userID", myApp.digitalid);//userid 
					params.put("group_id", myApp.getGroupId());
					return params;
				}
			};  
			stringRequest.setHeader(myApp.phpsessid);
			stringRequest.setTag(TAG);
			RequestQueueSingleton.getInstance(mContext).addToRequestQueue(stringRequest); 
		} catch (Exception e) { 
			e.printStackTrace();
		}
	}
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) { 
//			Toast.makeText(getApplicationContext(), position+","+id, Toast.LENGTH_SHORT).show();
			TrackerUser tu = datas.get(position-1);
			Intent intent = new Intent(ExpertsActivity.this,UserDetailActivity.class);
			intent.putExtra("userid", tu.trackId);
			intent.putExtra("username", tu.trackName);
			intent.putExtra("groupid", tu.trackGid);
			intent.putExtra("webId", tu.webId);
			startActivity(intent);
		}
	};
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_callback:
			this.finish();
			break;
		case R.id.btn_refresh:
			load();
			break;

		default:
			break;
		}
	}
	
	
	
	
	@Override
	protected void onStop() { 
		super.onStop(); 
		clear();
	}

	private void clear(){
		RequestQueueSingleton.getInstance(mContext).cancleAllReq(TAG);
//		datas.clear();
//		bitmapUtils = null;
//		actualListView = null;
//		mPullToRefreshListView = null;
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
		if(keyCode == KeyEvent.KEYCODE_BACK){
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	 
}
